package com.xzq.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzq.erp.context.BaseContext;
import com.xzq.erp.domain.dto.PageDTO;
import com.xzq.erp.domain.dto.ProductStockDTO;
import com.xzq.erp.domain.dto.WarehouseDTO;
import com.xzq.erp.domain.dto.WarehouseStockRecordDTO;
import com.xzq.erp.domain.po.ProductStock;
import com.xzq.erp.domain.po.SysUser;
import com.xzq.erp.domain.po.Warehouse;
import com.xzq.erp.domain.po.WarehouseStockRecord;
import com.xzq.erp.domain.query.ProductStockPageQuery;
import com.xzq.erp.domain.vo.ProductStockListVO;
import com.xzq.erp.domain.vo.ProductStockVO;
import com.xzq.erp.domain.vo.ProductVO;
import com.xzq.erp.enums.ResponseCodeEnum;
import com.xzq.erp.exception.BizException;
import com.xzq.erp.mapper.ProductStockMapper;
import com.xzq.erp.mapper.SysUserMapper;
import com.xzq.erp.mapper.WarehouseMapper;
import com.xzq.erp.mapper.WarehouseStockRecordMapper;
import com.xzq.erp.service.IProductStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品库存表 服务实现类
 * </p>
 *
 * @author xzq
 * @since 2025-05-26
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ProductStockServiceImpl extends ServiceImpl<ProductStockMapper, ProductStock> implements IProductStockService {

    private final WarehouseMapper warehouseMapper;

    private final WarehouseStockRecordMapper warehouseStockRecordMapper;

    private final SysUserMapper sysUserMapper;

    @Override
    public List<ProductStockVO> getProductStock(Long id) {
        List<ProductStock> list = lambdaQuery().eq(ProductStock::getProductId, id).list();
        if(CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        List<Long> warehouseIds = list.stream().map(ProductStock::getWarehouseId).collect(Collectors.toList());
        List<Warehouse> warehouses = warehouseMapper.selectBatchIds(warehouseIds);
        Map<Long, String> warehouseMap = warehouses.stream().collect(Collectors.toMap(Warehouse::getId, Warehouse::getName));
        List<ProductStockVO> vos = BeanUtil.copyToList(list, ProductStockVO.class);
        for(ProductStockVO vo : vos){
            vo.setWarehouseName(warehouseMap.get(vo.getWarehouseId()));
        }
        return vos;
    }

    @Override
    public PageDTO<ProductStockListVO> getProductStockList(ProductStockPageQuery query) {
        PageHelper.startPage(query.getCurrent(), query.getSize());
        // 注意Page继承了ArrayList，所以它是个集合对象
        Page<ProductStockListVO> page = this.baseMapper.getProductStockList(query);// 查询分页查询列表
        List<ProductStockListVO> result = page.getResult();
        if(CollectionUtils.isEmpty(result)){
            return PageDTO.empty(page.getTotal(), (long)page.getPages());
        }
        log.info("查询结果:{},{}", page.getPages(), page.getTotal());
        return PageDTO.of(page);
    }

    @Override
    public List<ProductStockListVO> getAllPurchaseLists() {
        ProductStockPageQuery query = new ProductStockPageQuery();
        query.setCurrent(1);
        query.setSize(0);
        return this.getProductStockList(query).getList();
    }

    @Override
    @Transactional
    public void updateProductRecord(WarehouseStockRecordDTO warehouseStockRecordDTO) {
        Integer status = warehouseStockRecordDTO.getStatus();
        lambdaUpdate()
                .eq(ProductStock::getId, warehouseStockRecordDTO.getProductStockId())
                .set(ProductStock::getStatus, status)
                .update();
        if(status == 2){
            // 减去库存信息
            lambdaUpdate()
                    .eq(ProductStock::getId, warehouseStockRecordDTO.getProductStockId())
                    .setSql("stock = stock - " + warehouseStockRecordDTO.getQuantity())
                    .ge(ProductStock::getStock, warehouseStockRecordDTO.getQuantity())
                    .update();
        }
        // 添加入库/出库信息
        WarehouseStockRecord warehouseStockRecord = new WarehouseStockRecord();
        warehouseStockRecord.setWarehouseId(warehouseStockRecordDTO.getWarehouseId());
        warehouseStockRecord.setProductId(warehouseStockRecordDTO.getProductId());
        warehouseStockRecord.setType(status);
        warehouseStockRecord.setQuantity(BigDecimal.valueOf(warehouseStockRecordDTO.getQuantity()));
        Long userId = BaseContext.getUserId();
        SysUser user = sysUserMapper.selectById(userId);
        if(Objects.nonNull(user)){
            warehouseStockRecord.setOperatorId(userId);
            warehouseStockRecord.setOperatorName(user.getNickname());
        }
        warehouseStockRecord.setOperationTime(LocalDateTime.now());
        warehouseStockRecord.setRemark(warehouseStockRecordDTO.getRemark());
        warehouseStockRecordMapper.insert(warehouseStockRecord);
    }

    @Override
    public void addProductStock(ProductStockDTO productStockDTO) {
        ProductStock productStock = BeanUtil.copyProperties(productStockDTO, ProductStock.class);
        save(productStock);
    }

    @Override
    public void updateProductStock(ProductStockDTO productStockDTO) {
        if(Objects.isNull(productStockDTO.getId())){
            throw new BizException(ResponseCodeEnum.PARAM_NOT_VALID);
        }
        ProductStock productStock = BeanUtil.copyProperties(productStockDTO, ProductStock.class);
        updateById(productStock);
    }
}
